<template>
  <el-dialog
    title="新增管理对象"
    width="500px"
    :visible.sync="visible"
    :before-close="handleClose"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="名称" prop="deviceName">
        <el-input v-model="ruleForm.deviceName" style="width: 280px" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="handleClose">取 消</el-button>
      <el-button size="small" type="primary" @click="submitForm('ruleForm')" :loading="loading">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { saveOrUpdateDevice } from '@/api/device'

export default {
  name: 'ManageObjectsDialog',
  props: {
    visible: {
      required: true,
      type: Boolean,
      default: false
    },
    editingDevice: {
      required: false,
      type: Object,
      default: null
    }
  },
  data() {
    return {
      ruleForm: {
        deviceName: ''
      },
      rules: {
        deviceName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  watch: {
    editingDevice: {
      handler(value) {
        if (value) {
          this.ruleForm.deviceName = value.deviceName
        } else {
          this.ruleForm.deviceName = ''
        }
      },
      deep: true
    }
  },
  methods: {
    handleClose() {
      this.resetForm('ruleForm')
      this.$emit('update:visible', false)
    },
    handleConfirm() {
      this.loading = true
      saveOrUpdateDevice({
        ...this.ruleForm,
        id: this.editingDevice ? this.editingDevice.id : undefined,
        pid: this.$route.meta.id,
        deviceLevel: 3
      }).then(({ success }) => {
        if (success) {
          this.$emit('onSuccess')
          this.handleClose()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.handleConfirm()
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
